<?php


namespace Cblood\Template;


use Cblood\Container\Overall;

class View
{
    /**
     * 模板文件存放路径
     * @var string
     */
    protected $viewPath;

    /**
     * 模板文件后缀名，通常用 php
     * @var string
     */
    protected $fileSuffix = 'php';

    public function __construct($viewPath)
    {
        $this->viewPath = $viewPath;
    }

    /**
     * 读取模板
     * @param $template
     * @param array $params
     * @return string
     */
    public function render($template, $params = [])
    {
        $file = $this->searchFilePath($template);
        extract($params);
        ob_start();
        include_once $file;
        $html = ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * 调用指定控制器返回的结果
     * 通常在html中使用
     * 两种方式：
     * 1. <?= Overall::view()->controller('headController')
     * 2. <?= Overall::view()->controller(['tailController' => 'method'])
     * @param $name
     * @param array $params
     * @return string
     */
    public function controller($name, $params = [])
    {
        if (is_array($name)) {
            list($className, $method) = $name;
            $controller = Overall::container()->instance($className);
            return Overall::container()->callMethod($controller, $method, $params);
        }

        /**
         * @var $controller TemplateController
         */
        $controller = Overall::container()->instance($name);
        return $controller->render($params);
    }

    /**
     * 查找模板文件
     * @param $template
     * @return string   实际的文件路径
     * @throws \Exception
     */
    protected function searchFilePath($template)
    {
        $template = trim($template, '/');
        $filePath = rtrim($this->viewPath, '/');
        $filePath = $filePath . '/' . $template . '.' . trim($this->fileSuffix, '.');
        if (is_file($filePath)) {
            return $filePath;
        }

        throw new \Exception('模板文件不存在！');
    }

    /**
     * @param mixed $viewPath
     */
    public function setViewPath($viewPath)
    {
        $this->viewPath = $viewPath;
    }

    /**
     * @param mixed $fileSuffix
     */
    public function setFileSuffix($fileSuffix)
    {
        $this->fileSuffix = $fileSuffix;
    }
}